package com.jifeng.sterilizer.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jifeng.sterilizer.entity.ControllerEntity;
import com.jifeng.sterilizer.entity.DeviceEntity;
import com.jifeng.sterilizer.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtils {
    //    static String uri = "http://localhost:9002/oauth/check_token";
    static String uri = "http://39.99.162.224:9001/oauth/check_token";

    public static String getToken(String account, String password) {
        try {
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("client_id", "client");
            paramMap.put("client_secret", "secret");
            paramMap.put("grant_type", "password");
            paramMap.put("password", password);
            paramMap.put("username", account);

            String jsonStr = HttpUtil.post("http://39.99.162.224:9001/oauth/token", paramMap);
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
            Object data = jsonObject.get("data");
            String string = data.toString();
            JSONObject jsonObject2 = JSONUtil.parseObj(string);
            return jsonObject2.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取token", e.getMessage());
            return "";
        }
    }

    public static Map getTokenInfo(HttpServletRequest request) {
        try {
            String authorization = request.getHeader("Authorization");
            if (StringUtils.isEmpty(authorization)) {
                log.warn("方法：{}，错误信息：{}", "获取token中的用户信息", "token为空");
                return null;
            }
            int i = authorization.indexOf(" ");
            String token = authorization.substring(i + 1);
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                // 创建一个提交数据的容器
                List<BasicNameValuePair> parames = new ArrayList<>();
                parames.add(new BasicNameValuePair("token", token));

                HttpPost httpPost = new HttpPost(uri);
                httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                Map map = JSON.parseObject(result, Map.class);
                String info = JSON.toJSONString(map.get("info"));
                Map map2 = JSON.parseObject(info, Map.class);
                return map2;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void addDevice(DeviceEntity deviceEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                HttpPost httpPost = new HttpPost("http://39.99.162.224:9000/sterilizer/device/save");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(deviceEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addController(ControllerEntity controllerEntity) {
        /**
         * Post发送json数据
         */
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                HttpPost httpPost = new HttpPost("http://39.99.162.224:9000/sterilizer/controller/save");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(controllerEntity),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 上限|下限温度修改请求
    public static boolean setLimitTemp(String number, String upper, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setLimitTemp?id=" + number + "&temper=" + value + "&upper=" + upper;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 运行定时修改
    public static boolean setRunTime(String id, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setRunTime?id=" + id + "&time=" + value;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 加热状态修改
    public static boolean setheatCmd(String number, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setheatCmd?id=" + number + "&cmd=" + value;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 工作状态修改
    public static boolean setRunCmd(String number, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setRunCmd?id=" + number + "&cmd=" + value;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 清洗保养
    public static boolean setCleanCmd(String number, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setCleanCmd?id=" + number + "&cmd=" + value;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 后台/本机
    public static boolean setWorkMode(String number, String value) {
        String uri = "http://47.92.203.167:8081/hy360/setWorkMode?id=" + number + "&mode=" + value;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 定时设置
    public static boolean setTimerMode(Integer number, Object type, Object startflag, Object startmin, Object startlen, Object times, Object startHour) {
        String uri = "http://47.92.203.167:8081/hy360/setTimerMode?type=" + type + "&id=" + number + "&startflag=" + startflag + "&startHour=" + startHour + "&startmin=" + startmin + "&startlen=" + startlen + "&times=" + times;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

    // 设置系统时间 PC
    public static boolean setSystemTime(Object number, Object year, Object mon, Object day, Object hour, Object min, Object sec, Object week) {
        String uri = "http://47.92.203.167:8081/hy360/setSystemTime?id=" + number + "year=" + year + "&mon=" + mon + "&day=" + day + "&hour=" + hour + "&min=" + min + "&sec=" + sec + "&week=" + week;
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return true;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "发送请求调用下位机", e.getMessage());
            return false;
        }
    }

}
